package com.albaba.designpattern.decorator.text_002;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @author zx
 * @version 1.0
 * @description 具体装饰者类-对文件内容进行加密和解密
 * @date 2025/2/20 20:57
 */
public class EncryptionDataDecorator extends DataLoaderDecorator {


    public EncryptionDataDecorator(DataLoader dataLoader) {
        super(dataLoader);
    }


    @Override
    public String read() {
        return decrypt(super.read());
    }

    @Override
    public void write(String data) {
        String encrypt = encrypt(data);
        super.write(encrypt);
    }

    // 加密操作
    public String encrypt(String data) {
        try {
            return Base64.getEncoder().encodeToString(data.getBytes("UTF-8"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 解密操作
    public String decrypt(String data) {
        return new String(Base64.getDecoder().decode(data));
    }

    public static void main(String[] args) {
        DataLoaderDecorator decorator = new EncryptionDataDecorator(new BaseFileDataLoader("test.txt"));
        decorator.write("hello world");
        System.out.println(decorator.read());
    }
}
